import { ref } from 'vue'

const cascaderSelectOptions = ref([{}]),
  cascaderData = ref([]),
  levelMap = ref([])
let list = [],
  byValueData = []

function groupBy(data, field) {
  return data.reduce((acc, item) => {
    const key = item[field]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(item)
    return acc
  }, {})
}

// 递归构建树形结构
function buildRecursiveTree(data, fields) {
  if (fields.length === 0) return [] // 如果没有字段，返回空数组
  const [currentField, ...remainingFields] = fields

  const grouped = groupBy(data, currentField) // 按当前字段进行分组
  const tree = []
  Object.keys(grouped).forEach((key) => {
    const node = { [currentField]: key, [currentField + '_name']: key } // 当前节点

    const children = buildRecursiveTree(grouped[key], remainingFields) // 递归处理子字段
    if (children.length > 0) {
      node._tree = children // 如果有子节点，加入 _tree 属性
    }
    tree.push(node)
  })
  return tree
}

const typeChange = (e, index, scopeIndex = 0) => {
  // 获取该分类下的选项
  const filterData = cascaderData.value.find((item) => item.field1 == e)?._tree

  const levelObj = {}
  cascaderSelectOptions.value[scopeIndex] ||= {}
  cascaderSelectOptions.value[scopeIndex][`field${index}`] ||= []
  levelMap.value?.map((item) => {
    levelObj[item.key] ||= item.value
  })
  if (filterData) {
    filterData?.map((fitem) => {
      fitem.field2_name = levelObj[fitem.field2] || ''
      return fitem
    })
    cascaderSelectOptions.value[scopeIndex][`field${index}`] = [...filterData]
    inFiledChange(index, scopeIndex)
  }
}

const inFiledChange = (index, scopeIndex = 0) => {
  console.log(6666)

  const selectedField = `field${index}`,
    selectedValue = list.value[scopeIndex][`institutionFiled${index}`]
  // 更新字段
  const Index = parseInt(selectedField.replace('field', ''))
  // 找到与选定字段值匹配的第一个对象

  const matchedItem = byValueData.find((item) => item[selectedField] === selectedValue)
  if (matchedItem) {
    // 更新其他字段的值（条件是只更新操作字段之后的字段）
    Object.keys(matchedItem).forEach((key) => {
      if (key.startsWith('field')) {
        const fieldIndex = parseInt(key.replace('field', ''))
        if (Index <= fieldIndex && fieldIndex != 1) {
          const selectedString = matchedItem[`field${fieldIndex}`]
          const data = cascaderSelectOptions.value[scopeIndex][`field${fieldIndex - 1}`].find(
            (item) => item[`field${fieldIndex}`] == selectedString
          )
          cascaderSelectOptions.value[scopeIndex][`field${fieldIndex}`] ||= []
          cascaderSelectOptions.value[scopeIndex][`field${fieldIndex}`] = data?._tree || []
          // 更新其他字段的值为匹配的对象的值
          list.value[scopeIndex][`institutionFiled${fieldIndex}`] =
            data[`field${fieldIndex}`] || list.value[scopeIndex][`institutionFiled${fieldIndex}`]
        }
      }
    })
  }
}

export default ({ treeData, data, listValue, tempLevelList }) => {
  byValueData = JSON.parse(JSON.stringify(data).replaceAll('null', `""`))
  const byValuetreeData = JSON.parse(JSON.stringify(treeData).replaceAll('null', '""'))
  const fieldList = data[0] ? Object.keys(data[0])?.filter((item) => item.startsWith('field')) : []

  list = listValue
  levelMap.value = tempLevelList
  cascaderData.value = buildRecursiveTree(byValueData, fieldList)

  return { inFiledChange, typeChange, byValueData, byValuetreeData, cascaderSelectOptions }
}
